package com.btr.ivle;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.btr.ivle.R;
import com.btr.ivle.backgroud.AsyncTaskCompleteListener;
import com.btr.ivle.backgroud.DownloadFilesTask;
import com.btr.ivle.backgroud.GetWorkbinTask;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.DatabaseWorkbin;
import com.btr.ivle.helper.IsNetworkAvailable;
import com.btr.ivle.helper.WorkbinSeparatedListAdapter;

public class ViewWorkbinActivity extends SherlockListActivity implements 
	AsyncTaskCompleteListener<String> {
	
	private Context context = this;
	private GetWorkbinTask getWorkbinTask;
	private DownloadFilesTask downloadTask;
	private String WorkbinID, itemID, CourseCode;
	private Boolean fromSelf;
	private boolean isRefresh = false;
	private MenuItem item;
	private int nFolder = 0;
	private boolean needRefresh = false;
	
	public static String MSG_ID = "ViewWorkbinActivity.ID";
	public static String MSG_WORKBINID = "ViewWorkbinActivity.WORKBINID";
	public static String MSG_NEEDREFRESH = "ViewWorkbinActivity.NeedRefresh";
	
    public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Sherlock_Light); //Used for theme switching in samples
        super.onCreate(savedInstanceState);
        setContentView(R.layout.empty_workbin);
        
        Intent intent = getIntent();
        fromSelf = intent.getBooleanExtra("From", false);
        CourseCode = intent.getStringExtra(ListModuleItemActivity.EXTRA_MESSAGE_COURSECODE);
        
        try{
        	isRefresh = savedInstanceState.getBoolean("isRefresh");
    	}catch(Exception ex){
	    }
        
        if(fromSelf){
        	itemID = intent.getStringExtra(ViewWorkbinActivity.MSG_ID);
        	WorkbinID = intent.getStringExtra(ViewWorkbinActivity.MSG_WORKBINID);
        }
        else{
        	WorkbinID = intent.getStringExtra(ListModuleItemActivity.EXTRA_MESSAGE_ID);
        }
        setActionBar();
        getWorkbinFromDB();
        
    }
    
    @Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  super.onSaveInstanceState(savedInstanceState);
	  savedInstanceState.putBoolean("isRefresh", isRefresh);
	}
    
    private void getWorkbinFromDB(){
    	boolean setFolderTag = false, setFileTag = false;
    	DatabaseWorkbin db = new DatabaseWorkbin(this,IVLEToken.getUserID() + "_Workbin",null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID() + "_Workbin"; 
        String[] columns = new  String[] {db.ID,db.FolderName,db.AllowUpload,
        		db.FileName,db.UploadTime,db.FileSize,db.FileType,db.isDownloaded,
        		db.OpenDate, db.WorkbinID};
        String selection = null;
        String[] selectionArgs = null;
        if(fromSelf){
	        selection = db.ParentID + "=?";
			selectionArgs = new  String[] {itemID};
        }else{
        	selection = db.ParentID + " IS NULL AND " + db.WorkbinID + "=?";
        	selectionArgs = new  String[] {WorkbinID};
        }
        String orderBy = db.isFile + " ASC"; 
        String limit = null ; 
        Cursor c = db.getReadableDatabase().query(table, columns, 
        		selection, selectionArgs, null, null, orderBy, limit);
        c.moveToFirst();
        
        Map<String, String> map, tagMap;
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Calendar calendar = Calendar.getInstance();
        Date date;
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM hh:mma");
        for  ( int  i =  0 ; i < c.getCount(); i++) { 
        	map = new HashMap<String, String>();
        	map.put(db.ID, c.getString(0));
        	if(!c.isNull(1)){
        		if(!setFolderTag){
        			tagMap = new HashMap<String, String>();
        			tagMap.put("Tag", "Folder");
        			list.add(tagMap);
            		setFolderTag = true;
            	}
	        	map.put(db.FolderName, c.getString(1));
	        	map.put(db.AllowUpload, String.valueOf(c.getInt(2)));
	        	map.put(db.WorkbinID, c.getString(9));
	        	calendar.setTimeInMillis(Long.parseLong(c.getString(8)));
	        	date = calendar.getTime();
	        	map.put(db.OpenDate, dateFormat.format(date));
	        	nFolder++;
        	}else{
        		if(!setFileTag){
        			tagMap = new HashMap<String, String>();
        			tagMap.put("Tag", "Files");
        			list.add(tagMap);
            		setFileTag = true;
            	}
	        	map.put(db.FileName, c.getString(3));
	        	map.put(db.FileSize, c.getString(5));
	        	map.put(db.FileType, c.getString(6));
	        	
	        	calendar.setTimeInMillis(Long.parseLong(c.getString(4)));
	        	date = calendar.getTime();
	        	map.put(db.UploadTime, dateFormat.format(date));
        	}
        	if(c.getInt(7)==0)
        		map.put(db.isDownloaded, null);
        	
    		list.add(map);
	        c.moveToNext();
        }
        c.close();
        db.getReadableDatabase().close();
        db.close();
        //if(list!=null)
        	setListView(list);
    }
    
    public void getWorkbinOnline(){
    	if(!isRefresh)
	        if(!IVLEToken.isOffline()){
		        if(IsNetworkAvailable.check(context)){
		        	item.setActionView(R.layout.progressbarindeterminatesmall);
		        	getWorkbinTask = new GetWorkbinTask(this);
			        getWorkbinTask.execute(WorkbinID);
		        }else{
		        	IVLEToken.setOffline(true);
		        }
	        }
    }
    
    @Override
    public void onDestroy(){
    	if(this.getWorkbinTask!=null)
    		this.getWorkbinTask.cancel(true);
    	if(downloadTask!=null)
    		downloadTask.cancel(true);
    	super.onDestroy();
    }
    	
    public void onAsyncTaskComplete(String result) {
		getWorkbinFromDB();
		if(item!=null)
			item.setActionView(null);
		isRefresh = true;
	}
    
    @SuppressLint("ParserError")
	private void setListView(final List<Map<String, String>> list){
    	TextView tv = (TextView) findViewById(R.id.textView1);
    	if(list.size()>0){
    		tv.setVisibility(View.GONE);
	    	WorkbinSeparatedListAdapter adapter = new WorkbinSeparatedListAdapter(context, list);
	        setListAdapter(adapter);
	        
	        ListView lv = getListView();
	        lv.setTextFilterEnabled(true);
	        lv.setOnItemClickListener(new OnItemClickListener() {
	            public void onItemClick(AdapterView<?> parent, View view,
	                int position, long id) {
	            	if( position <= nFolder ){
		          	  Intent intent = new Intent(ViewWorkbinActivity.this, ViewWorkbinActivity.class);
		  	          intent.putExtra(MSG_ID, list.get(position).get("WorkbinID"));
		  	          intent.putExtra(MSG_WORKBINID, list.get(position).get("WorkbinWorkbinID"));
		  	          intent.putExtra("From", true);
		  	          intent.putExtra(ListModuleItemActivity.EXTRA_MESSAGE_COURSECODE, CourseCode);
		  	          startActivityForResult(intent, 0);
	            	}else{
	            		downloadTask = new DownloadFilesTask(context);
	            		downloadTask.execute(list.get(position).get("WorkbinID"), 
	            				list.get(position).get("WorkbinFileName"), 
	            				list.get(position).get("WorkbinFileSize"),
	            				WorkbinID,CourseCode);
	            		needRefresh = true;
	            	}
	            }
	          });
    	}else{
    		tv.setVisibility(View.VISIBLE);
    	}
	}
    
    private void setActionBar(){
    	final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(false);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setSubtitle(CourseCode);
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.layout.menu_refresh, menu);
        item = menu.findItem(R.id.refresh);
        if(!fromSelf && !IVLEToken.isOffline() 
        		&& IsNetworkAvailable.check(context)){
        	getWorkbinOnline();
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) 
    {
    	switch (item.getItemId()) {
	        case android.R.id.home:
	        	onBackPressed();
	        	break;
	        case R.id.refresh:
	        	isRefresh = false;
	        	this.item = item;
	        	getWorkbinOnline();
	        	break;
    	}
          return true;
    }
    
    public void onBackPressed(){
    	Intent intent = new Intent();
    	intent.putExtra(MSG_NEEDREFRESH, needRefresh);
    	setResult(Activity.RESULT_OK, intent);
    	super.onBackPressed();
    }
    
    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) {     
    	super.onActivityResult(requestCode, resultCode, data);
    	if(data.getBooleanExtra(ViewWorkbinActivity.MSG_NEEDREFRESH, false)){
    		getWorkbinOnline();
    		needRefresh = false;
    	}
    }
}
